import React, { useState,useEffect,useMemo } from "react";
import moment from 'moment';
import 'moment/locale/zh-cn';
import { Modal, Menu, Form, Input,message, Upload,Cascader,Radio,Checkbox,DatePicker ,Row,Col} from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import Options from '../../static/js/cities';
import {connect} from 'react-redux';
import axios from 'axios' ;
import locale from 'antd/es/date-picker/locale/zh_CN';
import * as qiniu from 'qiniu-js'
const { RangePicker } = DatePicker;
const CheckboxGroup = Checkbox.Group;
moment.locale('zh-cn');

function UserInfoEdit({ visible ,setVisible,UpateUserInfo,getUserInfo}) {
    
    const handleOk = function() {
        form.validateFields().then( async(res) => {
            let placestr = '';
            place.forEach(item =>{
              placestr += item + ' '
            })
            placestr = placestr.trim('') ;
            let checkstr = '';
           checkarr.forEach(item => {
             checkstr += item + ' '
           })
           checkstr = checkstr.trim('');
          let datas = {
            id:UpateUserInfo.userInfo.id,
            userid:UpateUserInfo.userInfo.id,
            username:res.username,
            sex:sex,
            place:placestr,
            learnedcode:checkstr,
            birth:birthtime,
            phone:res.phone? res.phone:null,
            img:imageUrl
          }
          let {data :ret}=await axios.post('/api/edituser',datas)  ;
          // console.log(ret) ;
          if (ret.ok ==0) {
            return message.error(ret.message);
          }
    
          message.success(ret.message) ;
          let { data: reg } = await axios.get("/ap/user");
          // console.log(res) ;
          if (reg.ok !== 0) {
            getUserInfo({ type: "getuser", data: reg.data });
            // getUserInfo({type:'getHistory',history:history})
          }
          handleCancel() ;
        }).catch(err => {

          console.log(err) ;
        })
    }
    const handleCancel = function() {
       form.resetFields() ;
        setVisible(prev=>!visible)
    }
    const vis = useMemo(()=> {
       return visible
    },[visible])
  const [form] = Form.useForm();
  const onFinish = function () {};
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImgUrl] = useState(null);
  const [sex,setSex] = useState('男') ;
  const [fileList,setFileList] = useState([]) ;
  const [qnToken,setqnToken] = useState({uptoken:'',key:''}) ;
  const [place,setPlace] = useState([]);
  const [checkarr,setCheckarr] = useState([]) ;
  const [birthtime,setBirthtime] = useState(null);
  const [phone,setPhone] = useState(null) ;
  const onChangeSex = (e) => {
      setSex(prev=> e.target.value) ;
  } 
  function range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  

  function onChange(value) {
    setPlace(prev => value) ;
  }
  function changeimage(file,filelist) {
        // if(file.status === 'done') {
          // console.log(file) ;
        // }
        setFileList(prev => [...fileList])
  }
  function beforeUpload() {
    return new Promise(async (reslove,reject) =>{
      let {data:res} = await axios.get('/api/uptoken',{
        params:{
          userid:UpateUserInfo.userInfo.id,
        }
      }) ;
      if(res.ok == 0){
        return message.error(res.message) ;
      }
      setqnToken(prev => res);
      reslove();
    })
   }

  const complete = function(res) {
    if(res.hash&&res.key) {
      setImgUrl(prev=> 'http://imaegs.chenzefan.xyz/'+res.key)
      message.success('上传图片成功');
    }else {
      message.error('上传图片失败')
    }
  }
  const ok = (value) => {
    setBirthtime(prev => moment(value._d).format('X'));
    // form.setFieldsValue({birth:moment(value._d).format('X')}) ;
  }
  const checkChange = (value) =>{
         setCheckarr(prev => value) ;
  }

  useEffect(() => {
    if(visible === true) {
        setImgUrl(prev => UpateUserInfo.userInfo.img)
        form.setFieldsValue({username:UpateUserInfo.userInfo.username})
        form.setFieldsValue({phone:UpateUserInfo.userInfo.phone})
        setSex(prev =>UpateUserInfo.userInfo.sex ) ;
        setBirthtime(prev => UpateUserInfo.userInfo.birth) ;
        setCheckarr(prev => UpateUserInfo.userInfo.learnedcode?  UpateUserInfo.userInfo.learnedcode.split(' ') : []) ;
        setPlace(prev => UpateUserInfo.userInfo.place? UpateUserInfo.userInfo.place.split(' '):[]);
        
   }
      return () => {
        Modal.destroyAll()
      }
  }, [visible])
  return (
    <Modal
      title="编辑个人信息"
      visible={vis}
      onOk={handleOk}
      okText="确认"
      className="userinfoModal"
      cancelText="取消"
      onCancel={handleCancel}
      
    >
      <Form
        labelAlign="left"
        labelCol={{ span: 6 }}
        name="basic"
        initialValues={{
          remember: true,
        }}
        form={form}
        onFinish={onFinish}
        
      >
        <Form.Item label="头像" name="avatar">
          <Upload
            name="file"
            fileList={fileList}
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            onChange={changeimage}
            onSuccess={complete}
        
            // headers={{
            //   authorization:localStorage.getItem('token') 
            // }}
            beforeUpload={beforeUpload}
            // 不是走axios 走antd自带 因为后端设置了token验证 所以 heders 要添加令牌
            action="http://up-z2.qiniu.com/"
            data={{token:qnToken.uptoken,key:qnToken.key}}
            //  beforeUpload={beforeUpload}
            //  onChange={this.handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
            ) : (
              <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">Upload</div>
              </div>
            )}
          </Upload>
        </Form.Item>
        <Form.Item
          label="用户名"
          name="username"
          hasFeedback
          rules={[
            {
              required: true,
              message: "必须填写用户名",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item label="出生日期" >
          <DatePicker
            showTime={{ format: 'hh:mm:ss' }}
            locale={locale}
            placeholder='请输入出生日期'
            format="YYYY-MM-DD HH:mm:ss"
            onOk={ok}
            defaultValue={birthtime==null ? null : moment(birthtime*1000)}
          />
        </Form.Item>
        <Form.Item label='电话号码' name='phone' rules={[{pattern:/^1[3456789]\d{9}$/,message:'手机号码必须填写正确'}]}>
            <Input placeholder='请输入电话号码'></Input>
        </Form.Item>
        <Form.Item label='所在地'>
        <Cascader defaultValue={place} options={Options} onChange={onChange} placeholder="请选择所在地" />
        </Form.Item>
        <Form.Item label='性别'>
        <Radio.Group onChange={onChangeSex} value={sex}>
        <Radio value={'男'}>男</Radio>
        <Radio value={'女'}>女</Radio>
        <Radio value={'双性'}>双性</Radio>
      </Radio.Group>
        </Form.Item>
        <Form.Item label='学过语言'>
        <CheckboxGroup
        //   options={['Java','PHP','JS','Python','Go','C++',"C#",'TS']}
          defaultValue={checkarr}
          onChange={checkChange}
        >
             <Row gutter={[0,12]}>
      <Col span={8}>
        <Checkbox value="JAVA">JAVA</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="PHP">PHP</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="JS">JS</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="Python">Python</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="Go">Go</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="TS">TS</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="C#">C#</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="C++">C++</Checkbox>
      </Col>
      <Col span={8}>
        <Checkbox value="其他">其他</Checkbox>
      </Col>
    </Row>
        </CheckboxGroup>
        </Form.Item>
    </Form>
    </Modal>
  );
}

export default connect(state=>state,(dispatch)=> {
  return {
    getUserInfo:(data) => dispatch(data)
  }
})(UserInfoEdit);
